package mysql

import (
	"bluebell/models"
	"database/sql"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
	"strings"
)

func CreatePost(p *models.Post) (err error) {

	sqlStr := `INSERT INTO post (post_id, author_id, community_id, title, content) VALUES (:post_id, :author_id, :community_id, :title, :content)`

	_, err = db.NamedExec(sqlStr, p)
	if err != nil {
		return
	}

	return
}

// 单个帖子
func GetPostDetailWithDB(id int64) (data *models.Post, err error) {
	sqlStr := `select post_id, title, content, author_id, community_id, create_time from post where post_id = ?`

	data = new(models.Post)

	err = db.Get(data, sqlStr, id)

	if err != nil {
		if err == sql.ErrNoRows {
			zap.L().Error("不存在的帖子")
			err = ErrInvalidID
			return
		}
	}
	return
}
func GetPostList(offset int64) (data []*models.Post, err error) {
	sqlStr := `select post_id, title, content, author_id, community_id, create_time from post order by create_time desc limit ?, ?`

	err = db.Select(&data, sqlStr, (offset-1)*3, offset*3)
	if err != nil {
		if err == sql.ErrNoRows {
			zap.L().Error("一条帖子也没有")
		}
		return

	}
	return
}

// 根据 id 列表，查询数据
func GetPostListWithIDS(ids []string) (data []*models.Post, err error) {
	// 初始化返回值
	data = make([]*models.Post, 0, len(ids))
	//
	sqlStr := `select post_id, title, content, author_id, community_id, create_time from post where post_id in (?) order by FIND_IN_SET(post_id, ?)`
	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		zap.L().Error("根据从redis查询的post_id列表到mysql查询详情失败！", zap.Error(err))
		return
	}
	query = db.Rebind(query)
	err = db.Select(&data, query, args...) //
	return

}
